package com.example.demo.algorithm.sort;

import java.util.PriorityQueue;
import java.util.Stack;

public class quickSort {
    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 5, 4, 7, 6, 9, 8};
        quickSort2(arr, 0, arr.length - 1);
        for (int i : arr) {
            System.out.print(i);
        }
    }

    public static void quickSort(int[] arr, int left, int right) {
        if (left < right) {
            int mid = partition(arr, left, right);
            quickSort(arr, left, mid - 1);
            quickSort(arr, mid + 1, right);
        }
    }

//    public static int partition(int[] arr, int left, int right) {
//        int pivot = arr[left];
//        while (left < right) {
//            while (left < right && arr[right] >= pivot) right--;
//            arr[left] = arr[right];
//            while (left < right && arr[left] <= pivot) left++;
//            arr[right] = arr[left];
//        }
//        arr[left] = pivot;
//        return left;
//    }

    public static int partition(int[] arr,int left,int right){
        int pivot = arr[left];
        while(left < right){
            while(left < right && arr[right] >= pivot) right--;
            arr[left] = arr[right];
            while(left < right && arr[left] <= pivot) left++;
            arr[right] = arr[left];
        }
        arr[left] = pivot;
        return left;
    }


    //非递归实现快排
    public static void quickSort2(int[] arr,int left,int right){
        Stack<Integer> stack = new Stack<>();
        if(left < right){
            stack.push(right);
            stack.push(left);
            while(!stack.isEmpty()){
                int l = stack.pop();
                int r = stack.pop();
                int mid = partition(arr,l,r);
                if(l < mid - 1){
                    stack.push(mid - 1);
                    stack.push(l);
                }
                if(r > mid + 1){
                    stack.push(r);
                    stack.push(mid + 1);
                }
            }
        }
    }

}
